<template>
    <el-dialog :before-close="handleClose" :visible="dialogVisible" :title="title" width="40%">
        <span class="tree-top">
            <el-button type="primary" size="mini" @click="handleEXpandall(true)">展开</el-button>
            <el-button type="primary" size="mini" @click="handleEXpandall(false)">收起</el-button>
        </span>
        <div class="menu-container" :v-if="false">
            <el-tree
                ref="menuTree"
                v-loading="menuLoading"
                :data="menuData"
                size="mini"
                show-checkbox
                node-key="id"
                :render-content="renderContent"
                :props="defaultProps"
                default-expand-all
                element-loading-text="拼命加载中"
                class="tree-body"
                :check-strictly="true"
                @check="checkTree"
            />
        </div>
        <div class="clearfix" slot="footer">
            <div class="fl">
                <el-checkbox v-model="checkAll" @change="handleCheckAll">
                    <b>全选</b>
                </el-checkbox>
            </div>
            <div class="fr">
                <el-button type="primary" size="mini" @click="resetSelection">重置</el-button>
                <el-button type="primary" size="mini" :loading="authLoading" @click="submitAuthForm">提交</el-button>
                <el-button type="primary" size="mini" @click="closeDialog">关闭</el-button>
            </div>
        </div>
    </el-dialog>
</template>
<script>
import { dialogVisible } from '@/mixins/dialogMixin'
import { roleBindMenu, getAllMenuByApp, getMenuByRole } from '@/api/system/user'
export default {
    mixins: [dialogVisible],
    props: ['selectRole', 'title'],
    watch: {
        'selectRole.appId': {
            handler: function (newValue) {
                this.menuLoading = true
                getAllMenuByApp({ appId: newValue })
                    .then((res) => {
                        this.menuData = res.data
                    })
                    .finally(() => {
                        this.menuLoading = false
                    })

                // console.log(this.$refs.menuTree.store._getAllNodes().length)
            }
        },
        'selectRole.id': {
            handler: function (newValue) {
                getMenuByRole({ roleId: newValue }).then((res) => {
                    this.hasPermList = res.data
                    this.$refs.menuTree.setCheckedKeys(this.hasPermList)
                    this.isAllCheck()
                })
            }
        }
        // hasPermList: {
        //     handler: function(newValue, oldValue) {
        //         this.$refs.menuTree.setCheckedKeys(newValue)
        //     },
        //     deep: true
        // }
    },

    components: {},
    data() {
        return {
            // 是否展开所有节点
            authLoading: false,
            menuData: [],
            hasPermList: [],
            menuLoading: false,
            checkAll: false,
            currentRoleMenus: [],
            defaultProps: {
                children: 'children',
                label: 'resourceName'
            }
        }
    },
    mounted() {},
    methods: {
        // 是否是全选
        isAllCheck() {
            this.$nextTick(() => {
                console.log(this.$refs.menuTree.store._getAllNodes().length, this.hasPermList.length)
                this.checkAll = this.$refs.menuTree.store._getAllNodes().length === this.hasPermList.length
            })
        },
        // 收起与展开
        handleEXpandall(type) {
            this.$nextTick(() => {
                for (var i = 0; i < this.$refs.menuTree.store._getAllNodes().length; i++) {
                    this.$refs.menuTree.store._getAllNodes()[i].expanded = type
                }
            })
        },
        // 重置选择
        resetSelection() {
            this.checkAll = false
            this.$refs.menuTree.setCheckedNodes(this.currentRoleMenus)
        },
        // 全选操作
        handleCheckAll() {
            if (this.checkAll) {
                let allMenus = []
                this.checkAllMenu(this.menuData, allMenus)
                this.$refs.menuTree.setCheckedNodes(allMenus)
            } else {
                this.$refs.menuTree.setCheckedNodes([])
            }
        },
        // 递归全选
        checkAllMenu(menuData, allMenus) {
            menuData.forEach((menu) => {
                allMenus.push(menu)
                if (menu.children) {
                    this.checkAllMenu(menu.children, allMenus)
                }
            })
        },
        checkTree(data) {
            let thisNode = this.$refs.menuTree.getNode(data.id) // 获取当前节点
            let keys = this.$refs.menuTree.getCheckedKeys() // 获取已勾选节点的key值

            if (thisNode.checked) {
                // 选择子节点的时候默认选择父节点
                // 当前节点若被选中
                for (let i = thisNode.level; i > 1; i--) {
                    // 判断是否有父级节点
                    if (!thisNode.parent.checked) {
                        // 父级节点未被选中，则将父节点替换成当前节点，往上继续查询，并将此节点key存入keys数组
                        thisNode = thisNode.parent
                        keys.push(thisNode.data.id)
                    }
                }
            } else {
                for (let i = thisNode.level; i < 8; i++) {
                    // i<8 自己定义的
                    //取消父节点的时候默认取消子节点
                    // 判断是否有子级节点
                    if (thisNode.childNodes.length > 0) {
                        for (let j = 0; j < thisNode.childNodes.length; j++) {
                            let item = thisNode.childNodes[j]
                            if (item.checked) {
                                // 子级节点被选中，则将子节点替换成当前节点，往下继续查询，并将此节点key存入keys数组
                                thisNode = item
                                keys = keys.filter((keyItem) => {
                                    return keyItem !== thisNode.data.id
                                })
                            }
                        }
                    }
                }
            }

            this.$refs.menuTree.setCheckedKeys(keys) // 将所有keys数组的节点全选中
        },
        submitAuthForm() {
            if ('admin' == this.selectRole.name) {
                this.$message({
                    message: '超级管理员拥有所有菜单权限，不允许修改！',
                    type: 'error'
                })
                return
            }
            this.authLoading = true
            let keys = this.$refs.menuTree.getCheckedKeys()
            roleBindMenu({
                resIdList: keys,
                roleId: this.selectRole.id
            }).then((res) => {
                this.$message.success(res.msg)
                this.closeDialog()
                this.authLoading = false
            })
        },
        // 菜单的渲染dom处理
        renderContent(h, { node, data, store }) {
            if (data.type === 1) {
                return (
                    <div class="column-container">
                        <el-tag style="text-algin:center;" size="mini" type="primary">
                            {data.resourceName}
                        </el-tag>
                    </div>
                )
            } else if (data.type === 2) {
                return (
                    <div class="column-container">
                        <el-tag style="text-algin:center;" size="mini" type="success">
                            {data.resourceName}
                        </el-tag>
                    </div>
                )
            } else {
                return (
                    <div class="column-container">
                        <el-tag style="text-algin:center;" size="mini" type="danger">
                            {data.resourceName}
                        </el-tag>
                    </div>
                )
            }
        }
    }
}
</script>
//
<style lang="scss" scoped>
.tree-top {
    display: block;
    text-align: left;
    margin-left: 30px;
    margin-bottom: 15px;
}
// /deep/.el-dialog__body {
//   padding: 10px 20px;
// }
.tree-bottom {
    height: 20px;
    //   background: repeating-radial-gradient();
    padding-bottom: 10px;
}
.tree-body {
    min-height: 400px;
    max-height: 600px;
    overflow-y: auto;
    padding-left: 30px;
}
</style>
